import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;
import '../serve/file_serve.dart';

/// 简化版知识图谱节点
class SimpleKnowledgeNode {
  final String id;
  final String label;
  final int documentCount;
  final List<String> documents;
  final Color color;
  final double x;
  final double y;

  SimpleKnowledgeNode({
    required this.id,
    required this.label,
    required this.documentCount,
    required this.documents,
    required this.color,
    required this.x,
    required this.y,
  });
}

/// 简化版知识图谱连接
class SimpleKnowledgeEdge {
  final String sourceId;
  final String targetId;
  final int strength;

  SimpleKnowledgeEdge({
    required this.sourceId,
    required this.targetId,
    required this.strength,
  });
}

/// 简化版知识图谱组件
class SimpleKnowledgeGraphWidget extends StatefulWidget {
  final FileServe fileServe;
  final double width;
  final double height;
  final bool showLabels;
  final Function(SimpleKnowledgeNode)? onNodeTap;

  const SimpleKnowledgeGraphWidget({
    Key? key,
    required this.fileServe,
    this.width = 300,
    this.height = 200,
    this.showLabels = true,
    this.onNodeTap,
  }) : super(key: key);

  @override
  _SimpleKnowledgeGraphWidgetState createState() => _SimpleKnowledgeGraphWidgetState();
}

class _SimpleKnowledgeGraphWidgetState extends State<SimpleKnowledgeGraphWidget> {
  List<SimpleKnowledgeNode> nodes = [];
  List<SimpleKnowledgeEdge> edges = [];
  bool isLoading = true;
  String? errorMessage;
  SimpleKnowledgeNode? selectedNode;

  @override
  void initState() {
    super.initState();
    _loadKnowledgeGraph();
  }

  Future<void> _loadKnowledgeGraph() async {
    try {
      setState(() {
        isLoading = true;
        errorMessage = null;
      });

      // 读取tag.json文件
      final tagData = await _loadTagData();
      if (tagData.isEmpty) {
        setState(() {
          isLoading = false;
          errorMessage = '暂无标签数据';
        });
        return;
      }

      // 构建节点和边
      _buildGraphFromTagData(tagData);

      setState(() {
        isLoading = false;
      });
    } catch (e) {
      print('SimpleKnowledgeGraphWidget: 加载知识图谱失败: $e');
      setState(() {
        isLoading = false;
        errorMessage = '加载失败: $e';
      });
    }
  }

  Future<Map<String, List<String>>> _loadTagData() async {
    try {
      // 使用FileServe的方法获取全局标签数据
      return await widget.fileServe.getGlobalTags();
    } catch (e) {
      print('SimpleKnowledgeGraphWidget: 读取标签数据失败: $e');
      return {};
    }
  }

  void _buildGraphFromTagData(Map<String, List<String>> tagData) {
    nodes.clear();
    edges.clear();

    print('SimpleKnowledgeGraphWidget: 开始构建图谱，标签数据: ${tagData.length}');

    // 创建节点
    final colors = [
      Colors.blue.shade400,
      Colors.green.shade400,
      Colors.orange.shade400,
      Colors.purple.shade400,
      Colors.red.shade400,
      Colors.teal.shade400,
      Colors.indigo.shade400,
      Colors.pink.shade400,
    ];

    final entries = tagData.entries.toList();
    
    // 限制节点数量
    final maxNodes = min(entries.length, 15);
    final selectedEntries = entries.take(maxNodes).toList();
    
    print('SimpleKnowledgeGraphWidget: 创建${selectedEntries.length}个节点');
    
    // 使用固定布局避免物理引擎问题
    _createFixedLayout(selectedEntries, colors);
    
    // 创建边（基于共享文档）
    _createEdges();
    
    print('SimpleKnowledgeGraphWidget: 创建了${nodes.length}个节点，${edges.length}条边');
  }

  void _createFixedLayout(List<MapEntry<String, List<String>>> entries, List<Color> colors) {
    final centerX = widget.width / 2;
    final centerY = widget.height / 2;
    final radius = min(widget.width, widget.height) * 0.35;
    
    for (int i = 0; i < entries.length; i++) {
      final entry = entries[i];
      final tag = entry.key;
      final documents = entry.value;
      
      // 圆形布局
      final angle = (2 * pi * i) / entries.length;
      final x = centerX + radius * cos(angle);
      final y = centerY + radius * sin(angle);
      
      nodes.add(SimpleKnowledgeNode(
        id: tag,
        label: tag,
        documentCount: documents.length,
        documents: documents,
        color: colors[i % colors.length],
        x: x,
        y: y,
      ));
    }
  }

  void _createEdges() {
    for (int i = 0; i < nodes.length; i++) {
      for (int j = i + 1; j < nodes.length; j++) {
        final node1 = nodes[i];
        final node2 = nodes[j];
        
        // 找到共享的文档
        final sharedDocs = node1.documents
            .where((doc) => node2.documents.contains(doc))
            .toList();
        
        if (sharedDocs.isNotEmpty) {
          edges.add(SimpleKnowledgeEdge(
            sourceId: node1.id,
            targetId: node2.id,
            strength: sharedDocs.length,
          ));
        }
      }
    }
  }

  double _getNodeRadius(SimpleKnowledgeNode node) {
    // 增大基础半径，让节点更明显
    return 15 + (node.documentCount * 3).clamp(0, 20).toDouble();
  }

  void _onNodeTap(SimpleKnowledgeNode node) {
    setState(() {
      selectedNode = selectedNode == node ? null : node;
    });
    
    if (widget.onNodeTap != null) {
      widget.onNodeTap!(node);
    }
  }

  @override
  Widget build(BuildContext context) {
    print('SimpleKnowledgeGraphWidget build: 尺寸=${widget.width} x ${widget.height}, 加载中=$isLoading, 错误=$errorMessage, 节点数=${nodes.length}');

    if (isLoading) {
      return Container(
        width: widget.width,
        height: widget.height,
        color: Colors.grey[100],
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(strokeWidth: 2),
              SizedBox(height: 8),
              Text(
                '构建知识图谱中...',
                style: TextStyle(fontSize: 12, color: Colors.grey[600]),
              ),
            ],
          ),
        ),
      );
    }

    if (errorMessage != null) {
      return Container(
        width: widget.width,
        height: widget.height,
        color: Colors.red[50],
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, color: Colors.grey[400], size: 32),
              SizedBox(height: 8),
              Text(
                errorMessage!,
                style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      );
    }

    return Container(
      width: widget.width,
      height: widget.height,
      child: Stack(
        children: [
          // 背景
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.blue.shade50.withOpacity(0.3),
                  Colors.purple.shade50.withOpacity(0.2),
                  Colors.cyan.shade50.withOpacity(0.3),
                ],
              ),
              borderRadius: BorderRadius.circular(12),
            ),
          ),
          
          // 图谱画布
          CustomPaint(
            size: Size(widget.width, widget.height),
            painter: SimpleKnowledgeGraphPainter(
              nodes: nodes,
              edges: edges,
              selectedNode: selectedNode,
              showLabels: widget.showLabels,
            ),
          ),
          
          // 交互层
          ...nodes.map((node) => Positioned(
            left: node.x - _getNodeRadius(node),
            top: node.y - _getNodeRadius(node),
            child: GestureDetector(
              onTap: () => _onNodeTap(node),
              child: Container(
                width: _getNodeRadius(node) * 2,
                height: _getNodeRadius(node) * 2,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.transparent,
                ),
              ),
            ),
          )),
          
          // 节点信息提示
          if (selectedNode != null)
            Positioned(
              left: 8,
              top: 8,
              child: Container(
                padding: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 4,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      selectedNode!.label,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 12,
                      ),
                    ),
                    Text(
                      '${selectedNode!.documentCount} 个文档',
                      style: TextStyle(
                        fontSize: 10,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}

/// 简化版知识图谱绘制器
class SimpleKnowledgeGraphPainter extends CustomPainter {
  final List<SimpleKnowledgeNode> nodes;
  final List<SimpleKnowledgeEdge> edges;
  final SimpleKnowledgeNode? selectedNode;
  final bool showLabels;

  SimpleKnowledgeGraphPainter({
    required this.nodes,
    required this.edges,
    this.selectedNode,
    this.showLabels = true,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // 绘制边
    final edgePaint = Paint()
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    for (final edge in edges) {
      try {
        final source = nodes.firstWhere((n) => n.id == edge.sourceId);
        final target = nodes.firstWhere((n) => n.id == edge.targetId);
        
        final opacity = (edge.strength / 5).clamp(0.1, 0.6);
        edgePaint.color = Colors.grey.withOpacity(opacity);
        
        canvas.drawLine(
          Offset(source.x, source.y),
          Offset(target.x, target.y),
          edgePaint,
        );
      } catch (e) {
        continue;
      }
    }

    // 绘制节点
    for (final node in nodes) {
      final radius = 15 + (node.documentCount * 3).clamp(0, 20).toDouble();
      final isSelected = selectedNode == node;
      
      // 节点阴影
      final shadowPaint = Paint()
        ..color = Colors.black.withOpacity(0.3)
        ..maskFilter = MaskFilter.blur(BlurStyle.normal, 3);
      
      canvas.drawCircle(
        Offset(node.x + 2, node.y + 2),
        radius,
        shadowPaint,
      );
      
      // 节点主体
      final nodePaint = Paint()
        ..color = isSelected ? node.color : node.color.withOpacity(0.8)
        ..style = PaintingStyle.fill;
      
      canvas.drawCircle(
        Offset(node.x, node.y),
        radius,
        nodePaint,
      );
      
      // 节点边框
      if (isSelected) {
        final borderPaint = Paint()
          ..color = Colors.white
          ..strokeWidth = 2
          ..style = PaintingStyle.stroke;
        
        canvas.drawCircle(
          Offset(node.x, node.y),
          radius,
          borderPaint,
        );
      }
      
      // 节点标签
      if (showLabels) {
        // 对于长标签进行智能缩短
        String displayText = node.label;
        double fontSize = 12;
        
        if (node.label.length > 6) {
          displayText = node.label.substring(0, 5) + '...';
          fontSize = 10;
        } else if (node.label.length > 4) {
          fontSize = 10;
        }
        
        final textPainter = TextPainter(
          text: TextSpan(
            text: displayText,
            style: TextStyle(
              color: Colors.white,
              fontSize: fontSize,
              fontWeight: FontWeight.bold,
              shadows: [
                Shadow(
                  offset: Offset(0.5, 0.5),
                  blurRadius: 1,
                  color: Colors.black.withOpacity(0.5),
                ),
              ],
            ),
          ),
          textDirection: TextDirection.ltr,
        );
        
        textPainter.layout();
        
        final textOffset = Offset(
          node.x - textPainter.width / 2,
          node.y - textPainter.height / 2,
        );
        
        textPainter.paint(canvas, textOffset);
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
} 